package com.sunshine.litemusic.fragment.search;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.card.MaterialCardView;
import com.sunshine.litemusic.R;
import com.sunshine.litemusic.callback.MyCallBack;

import java.util.ArrayList;

/**
 * @author sunshine
 * @date 2020/5/29
 * 回收布局适配器，用于高性能展示歌曲列表
 */
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.RecyclerViewHolder> {

    private ArrayList<SearchModel.SearchBean> searchBeanArrayList;
    private Context context;
    private MyCallBack callBack;

    /**
     * @param searchBeanArrayList 搜索结果
     * @param callBack 回调接口 泛型是SearchBean类型
     */
    SearchAdapter(ArrayList<SearchModel.SearchBean> searchBeanArrayList, MyCallBack callBack) {
        this.searchBeanArrayList = searchBeanArrayList;
        this.callBack = callBack;
    }

    @NonNull
    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        this.context = parent.getContext();
        return new RecyclerViewHolder(LayoutInflater.from(context).inflate(R.layout.item_song, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, final int position) {
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callBack.callBack(searchBeanArrayList, position);
            }
        });
        Glide.with(context)
                .load(searchBeanArrayList.get(position).getAl().getPicUrl())
                .into(holder.imageViewAl);
        holder.songName.setText(searchBeanArrayList.get(position).getName());
        holder.alName.setText(searchBeanArrayList.get(position).getAl().getName());
        holder.singerName.setText(searchBeanArrayList.get(position).getAr());

    }

    @Override
    public int getItemCount() {
        return searchBeanArrayList.size();
    }

    /**
     * 用于绑定每一个Item的视图
     */
    class RecyclerViewHolder extends RecyclerView.ViewHolder{

        MaterialCardView cardView;
        ImageView imageViewAl;
        AppCompatTextView songName, singerName, alName;

        RecyclerViewHolder(@NonNull View itemView) {
            super(itemView);
            cardView = itemView.findViewById(R.id.cardView);
            imageViewAl = itemView.findViewById(R.id.imageView_al);
            songName = itemView.findViewById(R.id.song_name);
            singerName = itemView.findViewById(R.id.singser_name);
            alName = itemView.findViewById(R.id.al_name);
        }
    }
}
